<template>
	<avatar :selWidth="width" :selHeight="height" ref='avatar' fileType='png' :avatarSrc="avatarSrc" @upload="myUpload"
	 :quality="0.9" :avatarStyle="`width:${width};height:${height}`">
	</avatar>
</template>

<script>
	// selWidth	是	string	裁剪区域的宽，单位px或upx
	// selHeight	是	string	裁剪区域的高，单位px或upx
	// expWidth	否	string	设置导出图片宽度。默认值selWidth*屏幕像素密度，单位px或upx
	// expHeight	否	string	设置导出图片高度。默认值selHeight*屏幕像素密度，单位px或upx
	import avatar from "@/components/yq-avatar/yq-avatar.vue";
	export default {
		props: {
			value: {
				type: String,
				default: ''
			},
			//初始图片
			url: {
				type: String,
				default: '/static/icon/touxiang.png'
			},
			width: {
				type: String,
				default: '400rpx'
			},
			height: {
				type: String,
				default: '400rpx'
			},
			//如果base64=true,则返回base64格式数据，否则上传后返回id
			base64: {
				type: Boolean,
				default: false
			}

		},
		components: {
			avatar
		},
		data() {
			return {

				avatarSrc: null
			};
		},
		watch: {
			url(val) {
				this.avatarSrc = val
			}
		},
		created() {
			this.avatarSrc = this.url
		},
		methods: {
			async myUpload(res) {
				console.log(res);
				this.avatarSrc = res.path;
				console.log(this.avatarSrc)
				let base64 = await this.urlTobase64(this.avatarSrc)
				if (this.base64) {
					this.$emit('input',base64.fileData)
				} else {
					let id = await this.uploadFile(base64)
					console.log(this.id)
					this.$emit('input', id)
				}

			},
			urlTobase64(url) {
				return new Promise((resolve, reject) => {
					uni.getFileSystemManager().readFile({
						filePath: url, //选择图片返回的相对路径
						encoding: 'base64', //编码格式
						success: res => { //成功的回调
							let base64 = 'data:image/jpeg;base64,' + res.data //不加上这串字符，在页面无法显示的哦
							// this.dataList.picList.push(base64);
							// console.log(base64)
							let file = {
								fileData: base64,
								fileName: url
							};
							resolve(file)
							// this.uploadFile(file)
						},
						fail: err => {
							reject(err)
						}
					})
				})
			},
			// 上传文件
			uploadFile(file) {
				return new Promise((resolve, reject) => {
					uni.showLoading({
						title: "图片上传中",
						mask: true
					})
					// console.log(file)
					this.$http.post('common/file/upload', file).then(res => {
						console.log(res)
						if (res.code === 10000) {
						
							resolve(res.data.id)
							uni.hideLoading()
						}
					})
				})

			},
		}
	}
</script>

<style lang="scss">

</style>
